export default {
  namespaced: true,
  state:{
    cartList:JSON.parse(uni.getStorageSync('cartList')||'[]')
  },
  mutations:{
    getCartList(state,goods){
   const result=state.cartList.find(item=>item.goods_id==goods.goods_id)
   
   if(result){
     result.goods_count++
   }else{
     state.cartList.push(goods)
   }
   
    this.commit('myCart/saveToStorage')
    },
    updateState(state,goods){
  let result=state.cartList.find((x)=>{
    if( x.goods_id==goods.goods_id)
           return x
         })
         if(result){
           result.goods_state=goods.goods_state 
           this.commit('myCart/saveToStorage')
         }
 
 
    },
    removeCartBytId(state,goods){
   state.cartList=  state.cartList.filter(x=>{
        return x.goods_id!==goods.goods_id
      })
    
         this.commit('myCart/saveToStorage')
      
      
    },
    updatenum(state,goods){
   const result=   state.cartList.find(x=>{
        if(x.goods_id==goods.goods_id){
          return x
        }
      })
      if(result){
        result.goods_count=goods.goods_count
        this.commit('myCart/saveToStorage')
      }
    },
    saveToStorage(state){
     uni.setStorageSync('cartList',JSON.stringify(state.cartList))
          },
          setSate(state,gState){
            state.cartList.forEach(x=>{
              return x.goods_state=gState
            })
            this.commit('myCart/saveToStorage')
          }
   
  },
  actions:{
    setCartList({commit},goods){
      commit('getCartList',goods)
    },
    getAllChange({commit},gState){
      commit('setSate',gState)
    }
     
  },
  getters:{
    total(state){
      let sum=0
      state.cartList.forEach(item=>{
    sum=sum+item.goods_count
      })
      return sum
    },
    checkcount(state){
  return  state.cartList.filter(x=>x.goods_state).reduce((total,item)=>total+=item.goods_count,0)
    },
    checkTotal(state){
  return  state.cartList.filter(x=>x.goods_state).reduce((total,item)=>total+=item.goods_count*item.goods_price,0)
    }
  }
  
}